package com.hc.usb.impl;

import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbEndpoint;
import android.hardware.usb.UsbInterface;
import android.hardware.usb.UsbManager;
import android.util.Log;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;

public class USBConnection {
    private UsbDevice mUsbDevice;
    private UsbInterface mUsbInterface;
    private UsbEndpoint mReadPoint;
    private UsbEndpoint mWritePoint;
    private UsbDeviceConnection mUsbDeviceConnection;

    public USBConnection(UsbDevice mUsbDevice, UsbInterface mUsbInterface, UsbEndpoint mReadPoint, UsbEndpoint mWritePoint) {
        this.mUsbDevice = mUsbDevice;
        this.mUsbInterface = mUsbInterface;
        this.mReadPoint = mReadPoint;
        this.mWritePoint = mWritePoint;
    }

    public boolean open(UsbManager usbManager){
        mUsbDeviceConnection = usbManager.openDevice(mUsbDevice);
        if(mUsbDeviceConnection !=null){
            mUsbDeviceConnection.claimInterface(mUsbInterface,true);
            return true;
        }else {
            return false;
        }
    }

    public UsbDevice getUsbDevice() {
        return mUsbDevice;
    }

    public UsbEndpoint getReadPoint() {
        return mReadPoint;
    }

    public UsbEndpoint getWritePoint() {
        return mWritePoint;
    }

    public UsbDeviceConnection getUsbDeviceConnection() {
        return mUsbDeviceConnection;
    }

    public void close(){
        if(mUsbDeviceConnection !=null){
            mUsbDeviceConnection.releaseInterface(mUsbInterface);
            mUsbDeviceConnection.close();
        }
    }

    public byte[] readData(){
        if(mUsbDeviceConnection == null || mReadPoint ==null){
            return null;
        }
        int maxPacketSize = mReadPoint.getMaxPacketSize();
        byte[] buffer = new byte[maxPacketSize];
        int i = mUsbDeviceConnection.bulkTransfer(mReadPoint, buffer, buffer.length, 2000);
        if(i < 0){
            return null;
        }
        return buffer;
    }

    public boolean sendData(byte[] data){
        if(mUsbDeviceConnection == null || mWritePoint ==null){
            return false;
        }
        int i = mUsbDeviceConnection.bulkTransfer(mWritePoint, data, data.length, 2000);
        if(i < 0){
            return false;
        }else {
            return true;
        }
    }
}
